package com.duolebo.uteped_sdk.msg;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.duolebo.uteped_sdk.UTEPedEventHandler;
import com.duolebo.uteped_sdk.utils.Const;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.yc.nadalsdk.bean.Notify;
import com.yc.nadalsdk.bean.Response;
import com.yc.nadalsdk.ble.open.UteBleConnection;
import com.yc.nadalsdk.ble.open.UteBleDevice;
import com.yc.nadalsdk.constants.NotifyType;
import com.yc.nadalsdk.listener.DeviceNotifyListener;
import com.yc.nadalsdk.listener.FileService;
import com.yc.nadalsdk.log.LogUtils;
import com.yc.nadalsdk.watchface.bean.ApplyWatchFace;
import com.yc.nadalsdk.watchface.bean.ImageWatchFace;
import com.yc.nadalsdk.watchface.bean.ImageWatchFaceConfig;
import com.yc.nadalsdk.watchface.bean.WatchFaceCustomInfo;
import com.yc.nadalsdk.watchface.bean.WatchFaceFile;
import com.yc.nadalsdk.watchface.bean.WatchFaceInfo;
import com.yc.nadalsdk.watchface.bean.WatchFaceOnlineInfo;
import com.yc.nadalsdk.watchface.bean.WatchFaceOnlineOneInfo;
import com.yc.nadalsdk.watchface.bean.WatchFaceParams;
import com.yc.nadalsdk.watchface.open.WatchFaceUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class WatchFaceMessage extends BaseMessage implements DeviceNotifyListener {
    private static final String TAG = "WatchFaceMessage";
    private static final String PATH = "watchFace";

    private static final String M_getImageWatchFace = "getImageWatchFace";
    private static final String M_setImageWatchFace = "setImageWatchFace";
    private static final String M_getWatchFaceOnlineInformation = "getWatchFaceOnlineInformation";
    private static final String M_getWatchFaceOnlineClass = "getWatchFaceOnlineClass";
    private static final String M_downloadFile = "downloadFile";
    private static final String M_getServerWatchFace = "getServerWatchFace";
    private static final String M_getWatchFaceParams = "getWatchFaceParams";
    private static final String M_uploadWatchFace = "uploadWatchFace";
    private static final String M_applyWatchFace = "applyWatchFace";
    private static final String M_getWatchFaceInfo = "getWatchFaceInfo";
    private static final String M_downloadImageWatchFace= "downloadImageWatchFace";
    private static final String M_uploadImageWatchFace= "uploadImageWatchFace";

    private int watchFaceTotalCount = 0;//总个数
    private int watchFaceSecCount = 0;//多少组
    private final int watchFaceSec = 12;//每次获取9个表盘
    private String binFileName = "";//bin文件名称（包括后缀名.bin）
    private String binFileFolder = "";//bin文件下载保存的文件夹
    private int maxWatchFaceCount = 0;//最大在线表盘个数
    private boolean getWatchFaceSuccess = false;
    private WatchFaceParams watchFaceParams;

    /**
     * BaseCallback
     *
     * @param methodChannel methodChannel
     * @param eventHandler
     */
    public WatchFaceMessage(MethodChannel methodChannel, UTEPedEventHandler eventHandler) {
        super(methodChannel, eventHandler);
    }

    @Override
    public String getPath() {
        return PATH;
    }

    @SuppressLint("CheckResult")
    @Override
    public boolean methodCallConsumed(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
        if (!call.hasArgument(Const.KEY_METHOD))
            return false;

        if (super.methodCallConsumed(call, result))
            return true;

        UteBleConnection uteBleConnection = uteBleClient.getUteBleConnection();
        boolean consumed = true;
        String method = call.argument(Const.KEY_METHOD);
        assert method != null;
        switch (method) {
            case M_getImageWatchFace:
                if(!uteBleClient.isConnected()) {
                    result.success(false);
                    return true;
                }
                try{
                    Response<ImageWatchFace> watchFaceResponse = uteBleConnection.getImageWatchFace();
                    String watchFaceResponseStr = new Gson().toJson(watchFaceResponse);
                    LogUtils.i("M_getImageWatchFace:" + watchFaceResponseStr);

                    JsonObject jo = new Gson().fromJson(watchFaceResponseStr, JsonObject.class);
                    JsonObject rspJson = new JsonObject();
                    rspJson.add(Const.KEY_DATA, jo.get("mData"));
                    rspJson.addProperty(Const.KEY_SUCCESS, watchFaceResponse.isSuccess());

                    result.success(rspJson.toString());
                } catch (Exception e) {
                    result.success(false);
                    return true;
                }

                break;
            case M_downloadImageWatchFace:
                if(!uteBleClient.isConnected()) {
                    result.success(false);
                    return true;
                }

                Map<String, String> downloadImageWatchFaceParams = call.argument(Const.KEY_VALUE);
                String downloadImageWatchFaceName = downloadImageWatchFaceParams.get("name");
                int downloadImageWatchFaceIndex = Integer.valueOf(downloadImageWatchFaceParams.get("index"));
                String downloadImageWatchFaceNamePath = downloadImageWatchFaceParams.get("path")+"/";
                String filePath3 = downloadImageWatchFaceNamePath+"/";
                File file3 = new File(downloadImageWatchFaceNamePath, downloadImageWatchFaceName);
                LogUtils.i("filePath:"+filePath3+"|exists:"+file3.exists());
                uteBleConnection.downloadImageWatchFace(file3, downloadImageWatchFaceName, downloadImageWatchFaceIndex, new FileService.Callback() {
                    @Override
                    public void onProgress(int progress, int duration) {
                        LogUtils.i("downloadImageWatchFace:"+progress+"|"+duration);
                        Map<String, Object> map = new HashMap<>();
                        map.put(Const.KEY_PATH, getPath());
                        map.put(Const.KEY_METHOD, M_downloadImageWatchFace);
                        map.put(Const.KEY_PROGRESS, progress);
                        map.put(Const.KEY_DURATION, duration);
                        eventHandler.publishEvent(map);
                    }

                    @Override
                    public void onCompleted() {
                        Map<String, Object> map = new HashMap<>();
                        map.put(Const.KEY_PATH, getPath());
                        map.put(Const.KEY_METHOD, M_downloadImageWatchFace);
                        map.put(Const.KEY_ACTION, Const.ACTION_COMPLETE);
                        eventHandler.publishEvent(map);
                        result.success(true);
                    }

                    @Override
                    public void onFail(int errCode, Throwable throwable) {
                        Map<String, Object> map = new HashMap<>();
                        map.put(Const.KEY_PATH, getPath());
                        map.put(Const.KEY_METHOD, M_downloadImageWatchFace);
                        map.put(Const.KEY_ACTION, Const.ACTION_FAILED);
                        map.put(Const.KEY_ERROR_CODE, errCode);
                        eventHandler.publishEvent(map);
                        result.success(false);
                    }
                });
                break;
            case M_setImageWatchFace:
                if(!uteBleClient.isConnected()) {
                    result.success(false);
                    return true;
                }

                try {
                    Map<String, String> setImageWatchFaceParams = call.argument(Const.KEY_VALUE);
                    String positionIndex = setImageWatchFaceParams.get("positionIndex");
                    ImageWatchFaceConfig imageWatchFaceConfig = new ImageWatchFaceConfig();
                    imageWatchFaceConfig.setPositionIndex(Integer.valueOf(positionIndex));

                    List<ImageWatchFaceConfig.ImageInfoConfig> infoConfigs = new ArrayList<>();
                    ImageWatchFaceConfig.ImageInfoConfig infoConfig = new ImageWatchFaceConfig.ImageInfoConfig();
                    infoConfig.setIndex(Integer.valueOf(setImageWatchFaceParams.get("index")));
                    infoConfig.setName(setImageWatchFaceParams.get("name"));
                    infoConfigs.add(infoConfig);

                    imageWatchFaceConfig.setImageInfoConfigList(infoConfigs);
                    Response<ImageWatchFaceConfig> imageWatchFaceConfigResponse = uteBleConnection.setImageWatchFace(imageWatchFaceConfig);
                    String imageWatchFaceConfigResponseStr = new Gson().toJson(imageWatchFaceConfigResponse);
                    LogUtils.i("setImageWatchFace ==>>> " + imageWatchFaceConfigResponseStr);

                    JsonObject jo = new Gson().fromJson(imageWatchFaceConfigResponseStr, JsonObject.class);
                    JsonObject rspJson = new JsonObject();
                    rspJson.add(Const.KEY_DATA, jo.get("mData"));
                    rspJson.addProperty(Const.KEY_SUCCESS, imageWatchFaceConfigResponse.isSuccess());

                    result.success(rspJson.toString());
                } catch (Exception e) {
                    result.success(false);
                    return true;
                }

                break;
            case M_uploadImageWatchFace:
                if(!uteBleClient.isConnected()) {
                    result.success(false);
                    return true;
                }

                Map<String, String> uploadFileParams = call.argument(Const.KEY_VALUE);
                LogUtils.i("M_uploadImageWatchFace uploadFileParams:"+uploadFileParams);
                String width = uploadFileParams.get("width");
                String height = uploadFileParams.get("height");
                String pat4 = uploadFileParams.get("path");
                int uploadImageWatchFaceIndex = Integer.parseInt(uploadFileParams.get("index"));

                String imagePath = uploadFileParams.get("path"); // JPG图像文件路径
                String savePath = imagePath.replace(".jpg", "1.jpg");
                File originalFile = new File(imagePath);
                Bitmap originalImage = BitmapFactory.decodeFile(originalFile.getAbsolutePath());

                if(originalImage.getWidth()!=Integer.parseInt(width) || originalImage.getHeight()!=Integer.parseInt(height)) {
                    // 计算缩放比例
                    float scaleX = (float) Integer.parseInt(width) / originalImage.getWidth();
                    float scaleY = (float) Integer.parseInt(height) / originalImage.getHeight();
                    Matrix matrix = new Matrix();
                    matrix.postScale(scaleX, scaleY);
                    Bitmap resizedImage = Bitmap.createBitmap(originalImage, 0, 0, originalImage.getWidth(), originalImage.getHeight(), matrix, true);

                    try {
                        FileOutputStream fos = new FileOutputStream(savePath);
                        resizedImage.compress(Bitmap.CompressFormat.JPEG, 70, fos);
                        fos.flush();
                        fos.close();
                        LogUtils.i("bitmap resized compress=====" + savePath);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                File temp = new File(savePath.substring(0, savePath.lastIndexOf("/")), savePath.substring(savePath.lastIndexOf("/")+1));
                LogUtils.i("M_uploadImageWatchFace temp:"+temp.getPath()+"|"+temp.getName());

                uteBleConnection.uploadImageWatchFace(temp, uploadImageWatchFaceIndex, new FileService.Callback() {
                    @Override
                    public void onProgress(int progress, int duration) {
                        LogUtils.i("uploadImageWatchFace >> "+progress+"|"+duration);
                        Map<String, Object> map = new HashMap<>();
                        map.put(Const.KEY_PATH, getPath());
                        map.put(Const.KEY_METHOD, M_uploadImageWatchFace);
                        map.put(Const.KEY_ACTION, Const.ACTION_PROGRESS);
                        map.put(Const.KEY_PROGRESS, progress);
                        map.put(Const.KEY_DURATION, duration);
                        eventHandler.publishEvent(map);
                    }

                    @Override
                    public void onCompleted() {
                        Map<String, Object> map = new HashMap<>();
                        map.put(Const.KEY_PATH, getPath());
                        map.put(Const.KEY_METHOD, M_uploadImageWatchFace);
                        map.put(Const.KEY_ACTION, Const.ACTION_COMPLETE);
                        eventHandler.publishEvent(map);
                        result.success(true);
                    }

                    @Override
                    public void onFail(int i, Throwable throwable) {
                        Map<String, Object> map = new HashMap<>();
                        map.put(Const.KEY_PATH, getPath());
                        map.put(Const.KEY_METHOD, M_uploadImageWatchFace);
                        map.put(Const.KEY_ACTION, Const.ACTION_FAILED);
                        map.put(Const.KEY_ERROR_CODE, i);
                        eventHandler.publishEvent(map);
                        result.success(false);
                    }
                });
                break;
            case M_getWatchFaceOnlineInformation:
                if(!uteBleClient.isConnected()) {
                    result.success(false);
                    return true;
                }
                new Thread(() -> {
                    String config = call.argument(Const.KEY_VALUE);
                    String languageType = "zh";
                    String refresh = "true";
                    try {
                        JSONObject jsonObj = new JSONObject(config);
                        languageType = jsonObj.optString("languageType");
                        refresh = jsonObj.optString("refresh");

                        if(TextUtils.equals(refresh, "true")) {
                            watchFaceSecCount = 0;
                        }

                        int start = watchFaceSec * watchFaceSecCount;
                        int end = watchFaceTotalCount>0?Math.min(watchFaceTotalCount, watchFaceSec * (watchFaceSecCount + 1) - 1):watchFaceSec * (watchFaceSecCount + 1) - 1;

                        if (watchFaceSecCount != 0 && watchFaceSecCount * watchFaceSec >= watchFaceTotalCount) {
                            result.success(false);
                        } else {
                            watchFaceSecCount++;
                            LogUtils.i("watchFaceTotalCount:"+watchFaceTotalCount+"|watchFaceSecCount:"+watchFaceSecCount+"|start:"+start+"|end:"+(watchFaceSec * (watchFaceSecCount + 1) - 1)+"|"+end);

                            WatchFaceOnlineInfo info = WatchFaceUtil.getInstance().getWatchFaceOnlineInformation(start, end, languageType);
                            result.success(new Gson().toJson(info));
                            int flag = info.getFlag();
                            LogUtils.i("loadWatchFaceData flag =" + flag);
                            if(flag>0) {
                                watchFaceTotalCount = info.getTotalCount();
                                List<WatchFaceOnlineOneInfo> watchFaceOnlineOneInfoList = info.getWatchFaceOnlineOneInfoList();
                                LogUtils.i("size:"+watchFaceOnlineOneInfoList.size());
                            }
                        }
                    } catch (Exception e) {
                        LogUtils.i("jsonObj ::>>> "+e.getMessage());
                        result.success(false);
                    }
                }).start();
                break;

            case M_getWatchFaceOnlineClass:
//                languageType = "1";
//                List<WatchFaceOnlineClass> list = WatchFaceUtil.getInstance().getWatchFaceOnlineClass(languageType);
                break;

            case M_downloadFile:
                if(!uteBleClient.isConnected()) {
                    result.success(false);
                    return true;
                }

                Map<String, String> downloadFileParams = call.argument(Const.KEY_VALUE);
                String urlPath = downloadFileParams.get("url_path");
                String path = downloadFileParams.get("path")+"/";
                String fileName = urlPath.substring(urlPath.lastIndexOf("/") + 1);
                LogUtils.i("urlPath:"+urlPath+"|path:"+path+"|fileName:"+fileName);

                new Thread(()->{
                    int status = WatchFaceUtil.getInstance().downloadFile(urlPath, path, fileName);
                    result.success(status);
                }).start();
                break;
            case M_uploadWatchFace:
                if(!uteBleClient.isConnected()) {
                    result.success(false);
                    return true;
                }

                Map<String, String> uploadWatchFaceParams = call.argument(Const.KEY_VALUE);
                String url = uploadWatchFaceParams.get("url_path");
                String name = url.substring(url.lastIndexOf("/") + 1);
                String filePath = uploadWatchFaceParams.get("path")+"/"+name;
                File file = new File(filePath);
                LogUtils.i("filePath:"+filePath+"|exists:"+file.exists());
                WatchFaceFile watchFaceFile = new WatchFaceFile();
                watchFaceFile.setFile(file);
                uteBleConnection.uploadWatchFace(watchFaceFile, new FileService.Callback() {
                    @Override
                    public void onProgress(int progress, int duration) {
                        LogUtils.i("onProgress"+progress+"|"+duration);
                        Map<String, Object> map = new HashMap<>();
                        map.put(Const.KEY_PATH, getPath());
                        map.put(Const.KEY_METHOD, M_uploadWatchFace);
                        map.put(Const.KEY_ACTION, Const.ACTION_PROGRESS);
                        map.put(Const.KEY_PROGRESS, progress);
                        map.put(Const.KEY_DURATION, duration);
                        eventHandler.publishEvent(map);
                    }

                    @Override
                    public void onCompleted() {
                        LogUtils.i("onCompleted");

                        Map<String, Object> map = new HashMap<>();
                        map.put(Const.KEY_PATH, getPath());
                        map.put(Const.KEY_METHOD, M_uploadWatchFace);
                        map.put(Const.KEY_ACTION, Const.ACTION_COMPLETE);
                        eventHandler.publishEvent(map);
                        result.success(true);
                    }

                    @Override
                    public void onFail(int errorCode, Throwable throwable) {
                        LogUtils.i("onFail"+errorCode);
                        Map<String, Object> map = new HashMap<>();
                        map.put(Const.KEY_PATH, getPath());
                        map.put(Const.KEY_METHOD, M_uploadWatchFace);
                        map.put(Const.KEY_ACTION, Const.ACTION_FAILED);
                        map.put(Const.KEY_ERROR_CODE, errorCode);
                        eventHandler.publishEvent(map);
                        result.success(false);
                    }
                });
                break;
            case M_applyWatchFace:
                Map<String, Object> config = call.argument(Const.KEY_VALUE);
                if(!uteBleClient.isConnected() || config == null) {
                    result.success(false);
                    return true;
                }

                String id = "";
                String version = "";
                Integer operate = 1;
                try {
                    id = Objects.requireNonNull(config.get("id")).toString();
                    version = Objects.requireNonNull(config.get("version")).toString();
                    operate = (Integer) config.get("operate");
                } catch (Exception e) {
                    LogUtils.i("jsonObj ::>>> "+e.getMessage());
                }

                try {
                    ApplyWatchFace applyWatchFace = new ApplyWatchFace();
                    applyWatchFace.setId(id);
                    applyWatchFace.setVersion(version);
                    applyWatchFace.setOperate(operate);
                    Response<ApplyWatchFace> awfRsp = uteBleConnection.applyWatchFace(applyWatchFace);

                    JsonObject jo = new Gson().fromJson(new Gson().toJson(awfRsp), JsonObject.class);
                    JsonObject rspJson = new JsonObject();
                    rspJson.add(Const.KEY_DATA, jo.get("mData"));
                    rspJson.addProperty(Const.KEY_SUCCESS, awfRsp.isSuccess());

                    result.success(rspJson.toString());
                } catch (Exception e) {
                    result.success(false);
                    return true;
                }

                break;
            case M_getWatchFaceInfo:
                if(!uteBleClient.isConnected()) {
                    result.success(false);
                    return true;
                }
                try {
                    Response<WatchFaceInfo> wfRsp = uteBleConnection.getWatchFaceInfo(0);
                    JsonObject jo = new Gson().fromJson(new Gson().toJson(wfRsp), JsonObject.class);
                    JsonObject rspJson = new JsonObject();
                    rspJson.add(Const.KEY_DATA, jo.get("mData"));
                    rspJson.addProperty(Const.KEY_SUCCESS, wfRsp.isSuccess());

                    result.success(rspJson.toString());
                } catch (Exception e) {
                    result.success(false);
                    return true;
                }

                break;
            case M_getServerWatchFace:
                if(!uteBleClient.isConnected()) {
                    result.success(false);
                    return true;
                }
                new Thread(()->{
                    try {
                        List<WatchFaceCustomInfo> list = WatchFaceUtil.getInstance().getServerWatchFace();
                        String content = new Gson().toJson(list);
                        d("watch server face:" + content);
                        result.success(content);
                    } catch (Exception e) {
                        result.success(false);
                    }
                }).start();
                break;
            case M_getWatchFaceParams:
                if(!uteBleClient.isConnected()) {
                    result.success(false);
                    return true;
                }
                try {
                    Response<WatchFaceParams> response = uteBleConnection.getWatchFaceParams();
                    if (response.getErrorCode() == Const.CODE_SUCCESS) {
                        JsonObject jo = new Gson().fromJson(new Gson().toJson(response), JsonObject.class);
                        JsonObject rspJson = new JsonObject();
                        rspJson.add(Const.KEY_DATA, jo.get("mData"));
                        rspJson.addProperty(Const.KEY_SUCCESS, response.isSuccess());

                        result.success(rspJson.toString());
                    }
                    else {
                        result.success(false);
                    }
                } catch (Exception e) {
                    result.success(false);
                    return true;
                }
                break;
            default:
                consumed = false;
        }

        return consumed;
    }

    private void getWatchFaceParams() {
        LogUtils.i(TAG, "getWatchFaceParams =" + getWatchFaceSuccess);
        if (getWatchFaceSuccess) {
            reload();
        } else {
            //先获取表盘参数
            Response<WatchFaceParams> response = uteBleClient.getUteBleConnection().getWatchFaceParams();
            LogUtils.i(TAG, "getWatchFaceParams response=" + new Gson().toJson(response));
            //获取成功后，和服务器读取在线表盘信息
            if (response.isSuccess()) {
                getWatchFaceSuccess = true;
                watchFaceParams = response.getData();
                reload();
            }
        }
    }

    private void reload() {
        if (watchFaceSecCount != 0 && watchFaceSecCount * watchFaceSec >= watchFaceTotalCount) {
            // 没有更多表盘
        } else {
            String languageType = "zh";
            loadWatchFaceData(watchFaceSec * watchFaceSecCount, watchFaceSec * (watchFaceSecCount + 1) - 1, languageType);//获取第0个到第8个
            watchFaceSecCount++;
        }
    }

    /**
     * 访问服务器获取表盘信息并显示到界面
     *
     * @param startWatchFace 从第startWatchFace个表盘开始获取
     * @param endWatchFace   从第startWatchFace个表盘开始获取，获取到第endWatchFace个表盘
     * @param languageType   语言类型
     */
    @SuppressLint("CheckResult")
    private void loadWatchFaceData(int startWatchFace, int endWatchFace, String languageType) {
        try {
            Flowable.just(0).subscribeOn(Schedulers.io()).map(integer -> {
                WatchFaceOnlineInfo info = WatchFaceUtil.getInstance().getWatchFaceOnlineInformation(startWatchFace, endWatchFace, languageType);
                return info;
            }).observeOn(AndroidSchedulers.mainThread()).subscribe(info -> {
                int flag = info.getFlag();
                LogUtils.i("loadWatchFaceData flag =" + flag);
                if (flag > 0) {
                    watchFaceTotalCount = info.getTotalCount();
                    List<WatchFaceOnlineOneInfo> watchFaceOnlineOneInfoList = info.getWatchFaceOnlineOneInfoList();
                    LogUtils.i("watchFaceOnlineOneInfoList.size =====>>> "+watchFaceOnlineOneInfoList.size());
                    // 获取到表盘
                } else {
                    d("服务器没有该设备的在线表盘");
                }

            }, v -> {
//                ToastUtil.showToast(getContext(), getString(R.string.confire_is_network_available));
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //判断设备端的在线表盘是否已达上线
    private boolean isUpperLimit() {
        LogUtils.i("isUpperLimit ++++========>>> start");
        boolean result = false;
        Response<WatchFaceInfo> response = uteBleClient.getUteBleConnection().getWatchFaceInfo(0);
        LogUtils.i(TAG, "getWatchFaceInfo = " + new Gson().toJson(response));
        if (response.isSuccess()) {
            int count = 0;
            WatchFaceInfo watchFaceInfo = response.getData();
            List<WatchFaceInfo.WatchFace> watchFaceList = watchFaceInfo.getWorkFaceList();
            for (WatchFaceInfo.WatchFace watchFace : watchFaceList) {
                int type = watchFace.getType();
                if (WatchFaceUtil.watchFaceMode(WatchFaceInfo.WATCH_FACE_PRESET, type) ||
                        WatchFaceUtil.watchFaceMode(WatchFaceInfo.WATCH_FACE_GOOGLE_PRESET, type)) {

                } else {
                    count++;
                }
            }
            int maxCount = watchFaceParams.getWatchFaceCount();
            LogUtils.i(TAG, "maxCount = " + maxCount + ",count =" + count);
            if (count >= maxCount) {
                result = true;
            }
        }
        return result;
    }

    //删除表盘
    private void deleteWatchFace() {
        Response<WatchFaceInfo> response = uteBleClient.getUteBleConnection().getWatchFaceInfo(0);
        LogUtils.i(TAG, "getWatchFaceInfo = " + new Gson().toJson(response));
        if (response.isSuccess()) {
            WatchFaceInfo watchFaceInfo = response.getData();
            List<WatchFaceInfo.WatchFace> watchFaceList = watchFaceInfo.getWorkFaceList();
            if (watchFaceList != null && watchFaceList.size() > 0) {
                for (WatchFaceInfo.WatchFace watchFace : watchFaceList) {
                    int type = watchFace.getType();
                    //这里删除第一个，具体删除哪个APP可以根据自己的业务逻辑处理
                    boolean isSupDelete = WatchFaceUtil.watchFaceMode(WatchFaceInfo.WATCH_FACE_SUPPORT_DELETION, type);
                    if (isSupDelete) {
                        ApplyWatchFace applyWatchFace1 = new ApplyWatchFace();
                        applyWatchFace1.setId(watchFace.getId());
                        applyWatchFace1.setVersion(watchFace.getVersion());
                        applyWatchFace1.setOperate(ApplyWatchFace.WATCH_FACE_OPERATE_DELETE);
                        Response<ApplyWatchFace> deleteResponse = uteBleClient.getUteBleConnection().applyWatchFace(applyWatchFace1);
                        LogUtils.i(TAG, "deleteResponse = " + new Gson().toJson(deleteResponse));
                        break;
                    }
                }
            }
        }
    }

    @Override
    public void onNotify(@NonNull UteBleDevice uteBleDevice, @NonNull Notify notify) {
        d("imagewatchface onNotify: " + new Gson().toJson(notify));
        if (notify.getType() == NotifyType.FILE_UPLOAD_REQUIRED) {
            Map<String, Object> map = new HashMap<>();
            map.put(Const.KEY_PATH, getPath());
            map.put(Const.KEY_METHOD, M_setImageWatchFace);
            map.put(Const.KEY_VALUE, new Gson().toJson(notify));
            eventHandler.publishEvent(map);
        }
    }
}
